package com.baosight.risk.service.fltd.impl;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.baosight.iplat4j.core.util.DateUtils;
import com.baosight.risk.api.fltd.FltdNoticeToOAService;
import com.baosight.risk.api.fltd.FltdOATaskService;
import com.baosight.risk.api.xtaa.code.IXtaaCodeService;
import com.baosight.risk.base.service.BaseServiceImpl;
import com.baosight.risk.common.bean.BeanUtils;
import com.baosight.risk.common.utils.HttpClientUtil;
import com.baosight.risk.mapper.fltd.FltdNoticeMapper;
import com.baosight.risk.mapper.fltd.FltdTaskMapper;
import com.baosight.risk.service.fltd.entity.FltdNotice;
import com.baosight.risk.service.fltd.entity.FltdTask;
import com.baosight.risk.service.fltd.param.FltdNoticeQueryActiveParam;
import com.baosight.risk.service.xtaa.code.entity.XtaaCode;
import com.google.common.collect.Maps;

import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;

/**
 * 
 * @author zzw
 *
 */
@Slf4j
@Service
public class FltdNoticeToOAServiceImpl extends BaseServiceImpl<FltdNotice> implements FltdNoticeToOAService {
    @Autowired
    private FltdTaskMapper fltdTaskMapper;
    @Autowired
    private FltdNoticeMapper fltdNoticeMapper;
    @Autowired
    private IXtaaCodeService xtaaCodeService;

	@Autowired
	private FltdOATaskService fltdOATaskService;

	@Override
	public void sendOA(String jobId) throws Exception {
		FltdTask param = new FltdTask();
		param.setStatus("close");
		//param.setCompCode("BGTA");
		param.setCurrUserCode("037199");
		//param.setFlowNo("fengxianpilubaogao");
		List<FltdTask> fltdTasks = fltdTaskMapper.select(param);
		for (FltdTask task:fltdTasks) {
			//新增oa待办
			fltdOATaskService.deleteOA(task);
		}
	}

	@Override
	public void pushOA(String jobId) throws Exception {
		FltdTask param = new FltdTask();
		param.setStatus("open");
		//param.setCompCode("BGTA");
		//param.setCurrUserCode("037199");
		//param.setFlowNo("fengxianpilubaogao");
		List<FltdTask> fltdTasks = fltdTaskMapper.select(param);
		for (FltdTask task:fltdTasks) {
			//新增oa待办
			fltdOATaskService.insertOA(task);
		}
	}
	
	private void insertOA(FltdTask task){
		this.insertNotice(task);
        
		Map<String,Object> map = Maps.newHashMap();
		map.put("syscode","risk");
		map.put("flowid","risk-"+task.getFlowNo()+"-V1-"+task.getTodoGuid());
		map.put("requestname",task.getBizDesc());
		map.put("workflowname",task.getFlowName());
		map.put("nodename",task.getNodeName());
		map.put("pcurl",getUrlByDdCode("C"));
		map.put("isremark","0");//待办
		map.put("viewtype","0");//待办
		map.put("creator",task.getCurrUserCode());
		map.put("createdatetime",DateUtils.toDateStr(task.getCreateTime(),DateUtils.DEFAULT_DATETIME_PATTERN));
		map.put("receiver",task.getCurrUserCode());
		map.put("receivedatetime",DateUtils.toDateStr(task.getFactStartDate(),DateUtils.DEFAULT_DATETIME_PATTERN));
		map.put("receivets",String.valueOf(System.currentTimeMillis()));
		map.put("signver","V0");
		//JSONObject jsonObject = JSONObject.fromObject(map);
		String jsonData = JSON.toJSONString(map);

		String result = HttpClientUtil.doPostJson(getUrlByDdCode("A"),jsonData);
		JSONObject js = JSONObject.fromObject(result);
		if (!"1".equals(js.getString("operResult"))) {
			System.out.println("oa4.0 insert compensate error:"+js.getString("message"));
			log.error(js.getString("message"));
		}
	}
	
	private void deleteOA(String userCode){
		String url = getUrlByDdCode("B");
        //关闭所有活动的待办
		List<FltdNotice> activeNotices = new ArrayList<FltdNotice>();
		if(StringUtils.isBlank(userCode)){
			activeNotices = fltdNoticeMapper.selectAllActiveNotice();
		}else{
        	FltdNoticeQueryActiveParam param = new FltdNoticeQueryActiveParam();
        	param.setCurrUserCode(userCode);
			activeNotices = fltdNoticeMapper.selectActiveNotice(param);
		}
        
        for (FltdNotice notice : activeNotices) {
    		// TODO Auto-generated method stub
    		Map<String,Object> map = Maps.newHashMap();
    		map.put("syscode","risk");
    		map.put("flowid",notice.getFlowId());
    		map.put("userid",notice.getCurrUserCode());
    		//JSONObject jsonObject = JSONObject.fromObject(map);
    		String jsonData = JSON.toJSONString(map);

    		String result = HttpClientUtil.doPostJson(url,jsonData);
    		JSONObject js = JSONObject.fromObject(result);
    		if (!"1".equals(js.getString("operResult"))) {
    			System.out.println("oa4.0 delete compensate error:"+js.getString("message"));
    			log.error(js.getString("message"));
    		}else{
                notice.setStatus("close");
                fltdNoticeMapper.updateByPrimaryKeySelective(notice);
            }
        }
	}

    private String getUrlByDdCode(String ddCode){
    	List<XtaaCode> xtaaCodes = xtaaCodeService.selectDataByDDTypeCode("OA_URL");
    	for(XtaaCode xtaaCode : xtaaCodes){
    		if(ddCode.equals(xtaaCode.getDdCode())){
    			return xtaaCode.getDdDesc();
    		}
    	}
    	return null;
    }
    
    @Override
	public void synchroOA(String userCode){
        //关闭oa待办
        deleteOA(userCode);
        
		FltdTask param = new FltdTask();
		param.setStatus("open");
		param.setCurrUserCode(userCode);
        List<FltdTask> fltdTasks = fltdTaskMapper.select(param);
        for (FltdTask task:fltdTasks){
            //新增oa待办
            insertOA(task);
        }
	}
    
    private void insertNotice(FltdTask task){
        FltdNotice notice = new FltdNotice();
        BeanUtils.initBean(notice);
        notice.setFlowId("risk-"+task.getFlowNo()+"-V1-"+task.getTodoGuid());
        notice.setCurrUserCode(task.getCurrUserCode());
        notice.setCurrUserName(task.getCurrUserName());
        notice.setStatus("active");
        notice.setFrom("admin");
        notice.setTo(task.getCurrUserCode());
        notice.setUpdateBy(null);
        notice.setUpdateTime(null);
        fltdNoticeMapper.insert(notice);
    }
}
